// vim: set et sw=4 ts=4 sts=4 fdm=marker ff=unix fenc=utf8 nobomb:
/**
 * elements.js
 *      cache elements for popup.html in background.html
 *
 * @author mingcheng<i.feelinglucky#gmail.com>
 * @date   20009-11-26
 * @link   http://www.gracecode.com/
 */

Elements = (function() {
    var Util = YAHOO.util, Dom = Util.Dom, Event = Util.Event, Lang = YAHOO.lang;

    var TWITTER_HOME_URL_BASE = 'https://twitter.com/';

    var template = [
        '<h4 class="nick">',
            '<a title="{screen_name}\'s Homepage" href="https://twitter.com/',
            '{screen_name}">{name}</a>',
        '</h4>',
        //'<p class="time">{relative_time}</p>',
        '<p class="avatar">', 
            '<img width="48" height="48" src="{profile_image_url}" alt="{screen_name}"/></p>',
        '<p class="message">{formated_text}</p>',
        '<p class="act" param:id="{id}">{act}</p>',
        '<a href="#" act="favourite">Favourite</a>'
    ].join('');

    /**
     * 处理内容
     */
    var $process = function (str) {
        str = str.replace(/(http:\/\/[\w|\.|\/|\-|\=|\+|\?|\%|#]+)/g, '<a href="$1" title="$1">$1</a>');
        str = str.replace(/^@([\w|\_]+)/g, ' <a href="'+ TWITTER_HOME_URL_BASE +'$1" title="$1\'s Homepage">@$1</a>');
        return str.replace(/[^\w]@([\w|\_]+)/g, ' <a href="'+ TWITTER_HOME_URL_BASE +'$1" title="$1\'s Homepage">@$1</a>');
    }


    var unReadArray = [];

    /**
     * 渲染界面
     */
    var $draw = function(el, data) {
        if (!Lang.isArray(data)) return;
        var tmp = document.createDocumentFragment();
        for(var k = 0, length = data.length; k < length; k++) {
            var item = data[k];
            if (!Lang.isObject(item)) { continue; }

            var li = document.createElement('li'), sender = item.user || item.sender;
            var isme = !!(sender.screen_name == localStorage.getItem('status_last_login_username'));
            
            Dom.setAttribute(li, 'id', item.id);

            /**
             * 根据不同的 Tweets 指定不同的操作
             */
            if (isme) {
                var act = [
                    '<a href="#" act="delete" title="Delete this tweets">Delete</a>'
                ];
            } else {
                if (item.sender) {
                    var act = [
                      '<a href="#" act="direct" title="Send direct mesage">Direct</a>'/*,
                      '<a href="#" act="favourite" title="Add/remove favourite">Favourite</a>'
                      */
                    ];
                } else {
                    var act = [
                      '<a href="#" act="retweet" title="Retweet">Retweet</a>',
                      '<a href="#" act="reply" title="Reply @'+ sender.screen_name +'">Reply</a>'/*,
                      '<a href="#" act="favourite" title="Add/remove favourite">Favourite</a>'
                      */
                    ];
                }
            }

            // 根据 class 名称增加对应的样式
            if (item.in_reply_to_screen_name == localStorage['status_last_login_username']) {
                //Dom.addClass(li, 'reply');
                li.className = 'reply';
            }

            if (item.text.indexOf('@' + localStorage['status_last_login_username']) != -1) {
                //Dom.addClass(li, 'reply');
                li.className = 'reply';
            }

            if (isme) {
                //Dom.addClass(li, 'me');
                li.className = 'me';
            } else if (item.sender) {
                //Dom.addClass(li, 'direct');
                li.className = 'direct';
            } /* else if (item.) */

            Dom.setAttribute(li, 'screen_name', sender.screen_name);
            Dom.setAttribute(li, 'tweets_text', item.text);

            // format tweets content
            if (!item.formated_text) {
                item.formated_text = $process(item.text);

                // show relative time
                item.formated_text += '<p class="extra">';
                item.formated_text += '<span class="time">' + Helper.Func.relativeTime(item.created_at) + '</span>';

                // show Extra?
                if (Helper.Conf.Get('show_extra', 'yes') == 'yes') {
                    item.formated_text += '<span class="via">';
                    item.formated_text += ', from ' + item.source + ' ';

                    if (item.in_reply_to_screen_name && item.in_reply_to_status_id) {
                        item.formated_text += ', in reply to <a href="'+ TWITTER_HOME_URL_BASE +
                          item.in_reply_to_screen_name +'/status/' + item.in_reply_to_status_id 
                                +'/">@'+ item.in_reply_to_screen_name + '</a>';
                    }
                    item.formated_text += '</span>';
                }

                item += '</p>';
            }

            item.screen_name = sender.screen_name;
            item.name = sender.name;
            item.profile_image_url = sender.profile_image_url;
            item.act = act.join('');

            var isNew = false;
            if (unReadArray.indexOf(item.id) != -1) {
                isNew = true;
            }

            var html = Helper.Func.formatMessage(template, item);
            if (isNew){
                html += '<span class="new"></span>';
            }
            li.innerHTML = html;

            tmp.appendChild(li);
        }
        el.appendChild(tmp);
    }

    return {
        build: function(name, data) {
            var tmp = Dom.get('elements_' + name);
            unReadArray = Tweets.getUnreadArray();
            if (tmp) {
                tmp.innerHTML = '';
            } else {
                tmp = document.createElement('ul');
                Dom.setAttribute(tmp, 'id', 'elements_' + name);
                document.body.appendChild(tmp);
            }
            $draw(tmp, data);
        },

        getAll: function() {
            return _data;
        },

        set: function(name, innerHTML) {
            _data[name].innerHTML = innerHTML;
        },

        getHTML: function(name) {
            var tmp = Dom.get('elements_' + name);
            if (tmp) {
                return tmp.innerHTML;
            } else {
                return '';
            }
        }
    };
})();
